<?php

namespace addons\revolutionslider\models;

use Yii;
use app\base\behaviors\SetMaxSortableModel;

class Revolutionslider extends \app\base\ActiveRecord {

    public static function tableName() {
        return '{{%revolutionslider}}';
    }

    public function rules() {
        return [
            [['url'], 'safe'],
            [['weight'], 'integer'],
            ['captions', "safe"]
        ];
    }

    public function attributeLabels() {
        return [
            'revolutionslider_id' => Yii::t('addons', 'Revolutionslider ID'),
            'captions' => Yii::t('addons', 'Captions'),
            'url' => Yii::t('addons', 'Url'),
            'weight' => Yii::t('addons', 'Weight'),
        ];
    }

    public function beforeSave($insert) {
        if (parent::beforeSave($insert) == false) {
            return false;
        }
        $this->captions = serialize($this->captions);
        return true;
    }

    public function afterFind() {
        parent::afterFind();

        $captions = unserialize($this->captions);

        $result = [];

        if (!empty($captions)) {
            foreach ($captions as $caption) {
                $result[] = new CaptionForm($caption);
            }
        }

        $this->setAttribute("captions", $result);
    }

    public function behaviors() {
        $behaviors = [
            SetMaxSortableModel::className()
        ];

        $behaviors["thumbnailFile"] = [
            'class' => \app\attachment\behaviors\UploadBehavior::className(),
            'attribute' => 'thumbnail'
        ];
        return $behaviors;
    }
}
